#include "StdAfx.h"
#include "user_handler.h"
#include "user_reg_handler.h"
#include "user_login_handler.h"

namespace fly {

	namespace jld{

		namespace server {

			user_handler::user_handler()
				:handler()
				,user_hnd_(NULL)
				,account_exp_("[A-Za-z0-9]+")
			{

			}

			user_handler::~user_handler()
			{
				LOG_DEBUG("delete user handler");
				delete user_hnd_;
			}

			handler* user_handler::init_branch()
			{
				user_hnd_ = new user_reg_handler();
				user_hnd_->set_next_user(new user_login_handler());
				return this;
			}
			user_handler* user_handler::set_next_user(user_handler* hnd)
			{
				return user_hnd_ = hnd;
			}

			bool user_handler::handle_recv(recv_buf& recv_buf, send_buf& send_buf, conn_info& conn_info)
			{
				if (USER != recv_buf.pid())
				{
					return handler::handle_recv(recv_buf, send_buf, conn_info);
				}
				LOG_INFO("User handler");

				User user;
				if(!recv_buf.parse_from_recv(user))
				{
					LOG_ERR("parse user faild");
					return false;
				}
				if (!handle_user(user, recv_buf, send_buf, conn_info))
				{
					return false;
				}

				if (USER != recv_buf.pid())
				{
					return handler::handle_recv(recv_buf, send_buf, conn_info);
				}

				return true;
			}

			 bool user_handler::handle_user(User& user, recv_buf& recv_buf, send_buf& send_buf, conn_info& conn_info)
			 {
				if (NULL != user_hnd_)
				{
					return user_hnd_->handle_user(user, recv_buf, send_buf, conn_info);
				}
				LOG_ERR("without user handler can handle the request");
				return false;
			 }

			 bool user_handler::check_account(const User& user)
			 {
				if ((user.account().length() < 3) || (user.password().length() < 6))
				{
					LOG_ERR("account or password is not larger than the required length");
					return false;
				}
				if (!regex_match(user.account(), account_exp_))
				{
					LOG_ERR("account does not conform to the naming rules");
					return false;
				}
				return true;
			 }
		}
	}
}